/*
 * @文件描述: 数值单位调整
 * @版本: 
 * @作者: 周晨阳
 * @Date: 2021-05-24 15:15:48
 */
#include "unitCondi.h"

/**
 * @brief : 调整单位
 * @param {double} *value
 * @param {uint8_t} oriUnit
 * @param {uint8_t} desUnit
 * @return {*}
 */
void changeUnit(double *value, int8_t oriUnit, int8_t desUnit)
{
    int8_t dif = desUnit - oriUnit;
    *value = pow(*value, dif);
}
/**
 * @brief : 自动单位调整
 * @param {double} *value 输入以UNIT_NONE为单位的数值，将自动调整数值至最适合显示的值
 * @return {int8_t} 返回调整后的单位宏
 */
int8_t autoUnit(double *value, int8_t oriUnit)
{

    *value *= pow(10, oriUnit);
    double tmp = fabs(*value);
    if (tmp >= 1000 && tmp < 1000000)
    {
        *value *= 0.001f;
        return 3;
    }
    else if (tmp >= 1000000 && tmp < 1000000000)
    {
        *value *= 0.000001f;
        return 6;
    }
    else if (tmp >= 1000000000 && tmp < 1000000000000)
    {
        *value *= 0.000000001f;
        return 9;
    }

    else if (tmp >= 1 && tmp < 1000)
    {
        return UNIT_NONE;
    }
    else if (tmp >= 0.001 && tmp < 1)
    {
        *value *= 1000;
        return -3;
    }
    else if (tmp >= 0.000001 && tmp < 0.001)
    {
        *value *= 1000000;
        return -6;
    }
    else if (tmp >= 0.000000001 && tmp < 0.000001)
    {
        *value *= 1000000000;
        return -9;
    }
    else
    {
        return -1;
    }
}
/**
 * @brief : 自动junit调整
 * @param {double} *value 输入以UNIT_NONE为单位的数值，将自动调整数值至最适合显示的值
 * @return {int8_t} 返回调整后的单位宏
 */
void autojUnit(jUnit *j, int8_t oriUnit)
{
    j->unitCode = autoUnit(&(j->value), oriUnit);
    if (j->unitNewStr == NULL)
    {
        /* code */
        printf("unitNewStr null\n");
    }
    if (j->unitStr == NULL)
    {
        /* code */
        printf("unitStr null\n");
    }

    char *tmpStr = (char *)malloc(sizeof(char) * 3);
    switch (j->unitCode)
    {
    case -3:
        /* code */
        strcpy(tmpStr, "m");
        break;
    case -6:
        /* code */
        strcpy(tmpStr, "u");
        break;
    case -9:
        /* code */
        strcpy(tmpStr, "n");
        break;

    case 3:
        /* code */
        strcpy(tmpStr, "K");
        break;
    case 6:
        /* code */
        strcpy(tmpStr, "M");
        break;
    case 9:
        /* code */
        strcpy(tmpStr, "G");
        break;

    default:
        break;
    }
    strcat(tmpStr, j->unitStr);
    strcpy(j->unitNewStr, tmpStr);
    free(tmpStr);
}

jUnit *createjUnit(char *unit)
{
    jUnit *j = (jUnit *)malloc(sizeof(jUnit));
    j->unitCode = 0;
    j->value = 0;
    j->unitStr = unit;
    j->unitNewStr = (char *)malloc(sizeof(char) * 4);
    return j;
}
void freejUnit(jUnit *j)
{
    free(j->unitNewStr);
}